/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.proxy;

import com.aduib.boot.common.proxy.factory.ByteBuddyProxyFactory;
import com.aduib.boot.common.proxy.factory.CglibProxyFactory;
import com.aduib.boot.common.proxy.factory.JdkProxyFactory;
import com.aduib.boot.common.proxy.support.ByteBuddyProxy;
import com.aduib.boot.common.proxy.support.CglibProxy;
import com.aduib.boot.common.util.ClassUtils;

import java.util.Objects;

public class ProxyCreator {

    static final JdkProxyFactory jdkProxyFactory = new JdkProxyFactory();

    static final CglibProxyFactory cglibProxyFactory = new CglibProxyFactory();

    static final ByteBuddyProxyFactory byteBuddyProxyFactory = new ByteBuddyProxyFactory();

    public static Proxy createProxy(Class<?> targetClass, Object targetObject, Class<?>[] constructorArgTypes, Object[] constructorArgs) {
        if (targetClass.isInterface()) {
            return autoCreateProxy(jdkProxyFactory, targetClass, targetObject);
        } else {
            Class<?> superclass = ClassUtils.getSuperclass(targetClass);
            if (ClassUtils.getInterfaceClass(targetClass).length > 0 && (Objects.nonNull(superclass) && Object.class.equals(superclass))) {
                ByteBuddyProxy proxy = (ByteBuddyProxy) autoCreateProxy(byteBuddyProxyFactory, targetClass, targetObject);
                proxy.setConstructorArguments(constructorArgs, constructorArgTypes);
                return proxy;
            } else {
                CglibProxy proxy = (CglibProxy) autoCreateProxy(cglibProxyFactory, targetClass, targetObject);
                proxy.setConstructorArguments(constructorArgs, constructorArgTypes);
                return proxy;
            }
        }
    }

    private static Proxy autoCreateProxy(ProxyFactory proxyFactory, Class<?> targetClass, Object targetObject) {
        if (Objects.isNull(targetObject)) {
            return proxyFactory.createProxy(targetClass);
        } else {
            return proxyFactory.createProxy(targetObject);
        }
    }
}
